

local VERSION = "v1.07"  -- REMOVE COMMENTS --
local Sol = LibStub("Sol")

local MAX_HASH_VAL = 65535

ItemPreview = {}

ItemPreview.DefaultSettings = {
    UpdateSpeed = 30,
    HideInvalid = true,
    UpdateInterval = 15,
}

local isWorking = nil
local plusData = nil
local plusName = nil
local plusHash = 0

function ItemPreview:OnLoad(frame)
    frame:RegisterEvent("VARIABLES_LOADED")
    self.name = "ItemPreview"
end

function ItemPreview:OnEvent(frame, _event, _arg1, _arg2)
	if ( _event == "VARIABLES_LOADED" ) then
        Sol.config.CheckSettings("ItemPreview", ItemPreview.DefaultSettings)
        self.settings = ItemPreview_Settings
    
        Sol.config.CreateSlashCommand("item", self.ShowItem)
        Sol.config.CreateSlashCommand("skill", self.ShowSkill)
        Sol.config.CreateSlashCommand("plus", self.Plus)
        Sol.config.CreateSlashCommand("itempreview", self.PrintUsage)
        Sol.config.CreateSlashCommand("ipexample", self.PrintExamples)
        Sol.config.CreateSlashToHandleConfig(self.name, ItemPreview_ItemListFrame, "ipsearch")
        
        Sol.config.RestoreFrameBounds(self.name, ItemPreviewTooltip)
        
        self:RegisterWithAddonManager()
        self:LoadConfig()
    end
end

function ItemPreview:RegisterWithAddonManager() 
    if AddonManager then
        local addon = {
            name = self.name, 
            description = "Lets you preview items you don't have, plus and tier items to " ..
                          "see what the stats will be, and preview skills at different levels", 
            category = "Information",
            version = VERSION,
            author = "Alleris",
            slashCommands = "/item, /plus, /skill, /ipexample, /ipsearch",
            icon = "Interface/Addons/ItemPreview/Textures/ItemPreviewIcon",
            miniButton = ItemPreviewMiniButton,
            configFrame = ItemPreview_ItemListFrame,
        }
        
        if AddonManager.RegisterAddonTable then
            AddonManager.RegisterAddonTable(addon)
        else
            AddonManager.RegisterAddon(addon.name, addon.description, addon.icon, addon.category, 
                addon.configFrame, addon.slashCommands, addon.miniButton, addon.onClickScript)
        end
    else
        Sol.io.Print("ItemPreview loaded")
    end
end

function ItemPreview.ShowSkill(_, id)
    local self = ItemPreview
    if not id or #id == 0 then 
        self:PrintUsage()
        return
    end
    
    if Sol.string.StartsWith(id, "|Hskill") then
        id = id:sub(9, id:find(" ")-1)
    end

    id = Sol.string.Trim(id)
    if not id:find(" ") then
        id = id .. " 50"
    end
    
    self:ShowTooltip("|Hskill:" .. id .. "|h|h")
    local text = ItemPreviewTooltipTextLeft1:GetText()
    local color = Sol.constants.SKILL_COLOR
    if text then
        if not color then
            color = "FFFFFF"
        end
        local link = "|Hskill:" .. id .. "|h|cff" .. color .. "[" .. text .. "]|r|h"
    end
end

function ItemPreview.Plus(_, msg)
    local self = ItemPreview
    if not msg or #msg == 0 then
        self:PrintUsage()
        return
    end
    
    local numToPlus = msg:match("^%+(%d)")
    if numToPlus then
        msg = msg:sub(4)
    else
        numToPlus = "6"
    end
    local numToTier = msg:match("^t(%d)")
    if numToTier then
        numToTier = tonumber(numToTier)
        msg = msg:sub(4)
    end
    
    local runes = ""
    local hash = 0
    local data1, plus, data2, hashVal, name = msg:match("^(|Hitem:%x+ %x+ )(%x+)(.+) (%x+)(|h.+)$")
    if not data1 then
        data1, name = msg:match("^(|Hitem:%x+)(.+)$")
        if not data1 then
            local hex = Sol.math.DecToHex(tonumber(msg))
            data1, name = self:MakeItemLinkFromID(hex):match("^(|Hitem:%x+)(.+)$")
        end
        data1 = data1 .. " 1 "
        plus = "a64"
        data2 = " 0 0 0 0 0 0 0 1F40"
    else
        if plus:match("%x%x%x%x%x%x%x") then
            -- rune slots
            runes = plus:sub(0, 2)
            plus = plus:sub(5)
        elseif plus:match("%x%x%x%x%x") then
            plus = plus:sub(3)
        end
    end
    if numToTier and plus:match("%x%x%x") then
        local tier = Sol.math.DecToHex(10 + numToTier)
        plus = tier .. plus:sub(2)
    end
    if not numToTier or numToTier < 6 then
        plus = "0" .. plus
    end
    
    plusData = data1 .. runes .. numToPlus .. plus .. data2 .. " "
    plusName = name
    plusHash = 1
    isWorking = true
    Sol.io.Print("Working. Please wait...")
end

function ItemPreview.ShowItem(_, msg)
    local self = ItemPreview
    if not msg or #msg == 0 then
        self:PrintUsage()
        return
    end
    
    local linkToChat = false
    local trimmed = Sol.string.Trim(msg)
    if Sol.string.StartsWith(msg, "-c ") then
        linkToChat = true
        trimmed = Sol.string.Trim(trimmed:sub(4))
    end
    
    local startID, num = trimmed:match("(%d+) (%d+)")
    if not startID then startID = trimmed:match("(%d+)") end
    startID = tonumber(startID)
    num = tonumber(num)
    if not startID then return end
    if not num then num = 1 end
    
    local link = self:MakeItemLinkFromID(Sol.math.DecToHex(startID))
    ItemPreviewFrame_SetItemLink( ItemPreviewFrame, link )
    self:ShowTooltip(link)
end

function ItemPreview:ShowTooltip(link)
    if link then
        ItemPreviewTooltip:SetHyperLink(link)
        ItemPreviewTooltip:Show()
    else
        ItemPreviewTooltip:Hide()
    end
end

function ItemPreview:MakeItemLinkFromID(id)
    ItemPreviewTooltip:SetText("")
    ItemPreviewTooltip:SetHyperLink("|Hitem:" .. id .. "|h|h")
    ItemPreviewTooltip:Hide()
    local text = ItemPreviewTooltipTextLeft1:GetText()
    local color = Sol.color.ColorValuesToHexColor(ItemPreviewTooltipTextLeft1:GetColor())
    if text then
        if not color then
            color = "FFFFFF"
        end
        return "|Hitem:" .. id .. "|h|cff" .. color .. "[" .. text .. "]|r|h"
    end
end

function ItemPreview:PrintUsage()
    Sol.io.Print("ItemPreview usage: ")
    
    Sol.io.Print("/item id")
    Sol.io.Print("Previews the item with the specified ID")
    Sol.io.Print("-  id: an item ID, can be found in the URL of the item on RoM database websites")
    Sol.io.Print("")
    
    Sol.io.Print("/skill id [level]")
    Sol.io.Print("Previews the skill with the specified ID")
    Sol.io.Print("-  id: a skill ID, can be found in the URL of the item on RoM database websites")
    Sol.io.Print("-  level: optional - what level of the skill to preview")
    Sol.io.Print("")
    
    Sol.io.Print("/skill link")
    Sol.io.Print("Previews the specified skill at level 50")
    Sol.io.Print("-  link: a skill link, shift+click a skill to insert it")
    Sol.io.Print("")
    
    Sol.io.Print("/plus [+#] [t#] id")
    Sol.io.Print("/plus [+#] [t#] link")
    Sol.io.Print("Previews a plussed/tiered version of the item (may take a few seconds)")
    Sol.io.Print("-  +#: optional - how much to plus the item (default 6)")
    Sol.io.Print("-  t#: optional - how much to tier up the item (defaults to 0)")
    Sol.io.Print("-  id: an item ID, can be found in the URL of the item on RoM database websites")
    Sol.io.Print("-  link: an item link, shift+click an item to insert it")
    Sol.io.Print("")
    
    Sol.io.Print("/ipexample")
    Sol.io.Print("Shows examples of each of these to help you understand how to use it")
end

function ItemPreview:PrintExamples()
    local itemLink = "|cff0072bc[Frost Crossbow]|r"
    local spellLink = "|cff8080ff[Flame+35]|r"
    
    Sol.io.Print("ItemPreview Examples:")
    
    Sol.io.Print("/item 211549")
    Sol.io.Print("Previews the Frost Crossbow (id from http://www.runesdb.com/item.aspx?id=211549)")
    Sol.io.Print("/plus 211549")
    Sol.io.Print("Previews Frost Crossbow+6 ")
    Sol.io.Print("/plus t4 211549")
    Sol.io.Print("Previews Frost Crossbow+6, tier7 (4 tiers above default) ")
    Sol.io.Print("/plus +5 t4 211549")
    Sol.io.Print("Previews Frost Crossbow+5, tier7")
    Sol.io.Print("|cffffffff/plus " .. itemLink .. "|r")
    Sol.io.Print("Previews Frost Crossbow+6, with all stats of the linked item")
    Sol.io.Print("|cffffffff/plus +5 " .. itemLink .. "|r")
    Sol.io.Print("Previews Frost Crossbow+5, with all stats of the linked item")
    Sol.io.Print("")
    
    Sol.io.Print("/skill 491150")
    Sol.io.Print("Previews Flame at lvl50 (id from http://www.runesdb.com/spell.aspx?id=491150)")
    Sol.io.Print("/skill 491150 52")
    Sol.io.Print("Previews Flame at lvl52")
    Sol.io.Print("|cffffffff/skill " .. spellLink .. "|r")
    Sol.io.Print("Previews Flame at lvl50, assuming you linked flame from your skill book")
end


function ItemPreview:OnUpdate()
    if not isWorking then return end
    
    ItemPreviewTooltip:SetText("")
    for i = 0, self.settings.UpdateSpeed - 1 do
        local hash = plusHash + i
        if hash > MAX_HASH_VAL then
            isWorking = nil
            Sol.io.Print("Not found")
            ItemPreviewTooltip:Hide()
            return
        end
        
        local link = plusData .. Sol.math.DecToHex(hash) .. plusName
        ItemPreviewTooltip:SetHyperLink(link)
        if ItemPreviewTooltipTextLeft1:GetText() ~= "" then
            ItemPreviewFrame_SetItemLink( ItemPreviewFrame, link )
            self:ShowTooltip(link)
            isWorking = nil
            return
        end
    end
    plusHash = plusHash + self.settings.UpdateSpeed
end
